<template>
  <form-dialop
    :title="$t('common.edit')"
    :visible="visible"
    width="50%"
    @handleClose="handleClose"
		v-loading="loading"
  >
    <template #content>
      <el-form ref="form" :model="formData" label-position="right" label-width="100px" :rules="formRule">
        <el-form-item :label="$t('systemBack.version')" prop="title" name="title">
          <el-input style="width: 206px" v-model="formData.title" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <el-form-item :label="$t('systemBack.releaseDate')" prop="date" name="date">
          <el-date-picker style="width: 206px" v-model="formData.date" type="date" :placeholder="$t('systemBack.selectDate')" @keyup.enter.native="submit"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('common.description')" prop="descriptions" style="align-items: unset !important">
          <el-input v-model="formData.descriptions" v-show="false"></el-input>
          <div id="ed_markdown" ref="ed_markdown">
            <div v-html="htmlData"></div>
          </div>
        </el-form-item>
      </el-form>

    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialop from '@/components/Dialog/formDialog.vue';
import E from 'wangeditor';
import sparkMd5 from 'spark-md5'
export default Vue.extend({
  components: {
    FormDialop
  },
  props: {
    patchMethod: {
      type: Function,
      default() {
        return () => Promise.resolve();
      }
    }
  },
  data() {
    const validateGetVersion = (rule: any,value: any,callback: any) => {
      let exp = /^([1-9]\d|[1-9])(\.([1-9]\d|\d)){2}$/
      if(!exp.test(value)){
        return callback(new Error(this.$t("clientVersionLog.versionTitleTips") as any))
      }
      if(value !== this.oldTitle) {
        this.$pandaApi.apiGetVersionsDetail({ product_model: this.$route.query.product_model }).then((res: any)=>{
          const index = res.findIndex((versionDetail: any) => versionDetail.version_number == "v" + this.formData.title);
          if (index == -1) {
            return callback()
          } else {
            return callback(new Error((this as any).$t("clientVersionLog.getVersionError")))
          }
        })
      }
      return callback()
    }

    return {
      isChange: true,
      visible: false,
      loading: false,
      formData: {
        title: '',
        date: '',
        descriptions:''
      },
      md_id: '',
      ed: '',
      htmlData: '',
      formRule: {
        title:[
          { required: true, message: this.$t('clientVersionLog.VersionTitleTipsError'), trigger: 'blur' },
          { validator: validateGetVersion, trigger: 'blur'}
        ],
        date:[
          { required: true, message: this.$t('clientVersionLog.createDateTip'), trigger: 'blur' },
        ],
        descriptions:[
          {required: true, message: this.$t("clientVersionLog.descriptionTip"), tigger: 'blur'}
        ]
      },
      oldTitle: ''
    }
  },
  watch: {
    ed: {
      handler(val) {
        this.formData.descriptions = val.txt.html()
      },
      deep: true
    }
  },
  methods: {
    initMD(row: any) {
      (this as any).ed = new E('#ed_markdown');
      (this as any).ed.config.showFullScreen = false;
      (this as any).ed.config.menus = ['head','bold','fontName','fontSize','italic','underline','strikeThrough','indent','lineHeight','foreColor','backColor','link','list','todo','justify','quote','image','table','code','splitLine','undo','redo'];
      (this as any).ed.config.uploadImgServer = '/panda/faq/image/update';
      const that = this;
      (this as any).ed.config.customUploadImg = (resultFiles: any, insertImgFn: any) => {
        const fileReader = new FileReader()
        fileReader.readAsBinaryString(resultFiles[0]);
        fileReader.onload = (e: any) => {
          const md5 = sparkMd5.hashBinary(e.target.result);
          const headers = {
            "markdown-md5": md5,
            "Content-Disposition": "attachment;filename=" + encodeURIComponent(resultFiles[0].name),
            "Content-Type": "application/json"
          };
          that.$pandaApi.apiUploadImgs(resultFiles[0], headers).then((res: any) => {
            if(res.errno == 0 && res.data.length > 0) {
              insertImgFn(res.data[0].url);
            }
          }).catch((err: any)=>{
            console.log(err)
          })
        }
      };
      (this as any).ed.create();
      
    },
    init(row: any) {
      this.tenant_options = [];
      let str = row.version_number
			this.formData = {
					title:str.replace("v",""),
          date: row.created_at,
          descriptions: row.content
			};
      this.oldTitle  = this.formData.title
      this.md_id = row.id
      this.htmlData = row.content
      this.$nextTick(() => {
        if(!this.ed)
          this.initMD(row)
        if (this.$refs['form']) {
          (this.$refs['form'] as any).clearValidate();
        }
        (this as any).ed.txt.html(row.content);
      })
      this.visible = true;
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
					this.loading = true;
          (this as any).patchMethod(this.md_id,{
            "version_number": this.formData.title,
            "content": (this as any).ed.txt.html(),
            // "product_model": this.$route.query.data,
            "created_at": this.formData.date,
            "id":this.md_id
          }).then(() => {
            (this as any).visible = false;
          }).finally(() => {
            (this as any).loading = false;
          });
        }
      });
    },
    handleClose() {
      (this as any).formData = {
        title: ""
      };
      this.htmlData = "";
      this.md_id = "";
      // (this as any).ed.txt.clear();
      this.visible = false;
			this.loading = false;
      (this as any).ed.txt.clear();
    }
  }
})
</script>
<style scoped>
#ed_markdown {
  /* margin-left: 53px; */
  width: 120%;
}
</style>
